<?php
header('Access-Control-Allow-Origin: *');

if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    echo json_encode([]);exit;
}

$uploadMethod = 'oss';

// use Qiniu\Auth;
// use Qiniu\Storage\UploadManager;

use OSS\Core\OssException;
use OSS\OssClient;

if ($uploadMethod == 'oss') {
    $config = include "config.php";
    require_once './oss/autoload.php';
    $accessKeyId = $config['oss']['ossKey'];
    $accessKeySecret = $config['oss']['ossSecret'];
    $endpoint = $config['oss']['ossEndpoint'];
    $bucket = $config['oss']['ossBucket'];

    $content = file_get_contents($_FILES['file']['tmp_name']);

    $name = mt_rand(1, 99999999);

    $fileType = strtolower(strrchr($_FILES['file']['name'], '.'));
    $ossKey = date('Y-m-d', time()) . '/' . $name . $fileType;

    try {
        $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
        $ossClient->putObject($bucket, $ossKey, $content);

        $url = 'http://' . $bucket . '.' . $endpoint . '/' . $ossKey;
        echo json_encode(['result' => 0, 'url' => $url]);
    } catch (OssException $e) {
        print $e->getMessage();
    }
} else {
    date_default_timezone_set("Asia/chongqing");
    require_once './qiniu/autoload.php';

    $cdnUrl = 'http://qiniu1-cdn.wanshanghu.com/';
    $accessKey = '1s97HlU-MEvoehfax2XIhAHxPPiUwcZSX1O1tJKj';
    $secretKey = 'tlFW1m4UPgWsPEP_nvtXRZINHs5V_MLZ-Wm0VvwC';
    $bucket = 'test-qiniu-cdn';
    $upManager = new UploadManager();
    $auth = new Auth($accessKey, $secretKey);
    $token = $auth->uploadToken($bucket);

    $fileContent = file_get_contents($_FILES['file']['tmp_name']);

    $name = mt_rand(1, 99999999);

    list($ret, $error) = $upManager->put($token, date('Y-m-d', time()) . '/' . $name . '.png', $fileContent);

    $upManager->put($token, date('Y-m-d', time()) . '/thumb/200_200/' . $name . '.png', file_get_contents($cdnUrl . date('Y-m-d', time()) . '/' . $name . '.png-css200.200'));

    echo json_encode(['result' => 0, 'url' => $cdnUrl . $ret['key']]);

}
